import os, sys
from PIL import Image
from glob import glob
from pylab import *


def read_xy(anno_file, verbose=False):
    with open(anno_file) as fp:
        ret = fp.readline().split(',')
        if verbose:
            print(ret)
        if len(ret) > 9:
            return ret[1:9]
        else:
            return None


def visualise_dir(input_dir, im_save=False):
    annos = glob('{}/*.txt'.format(input_dir))
    for anno in annos:
        xys = read_xy(anno)
        im_path = os.path.splitext(anno)[0] + ".jpg"
        if os.path.exists(im_path):
            im = Image.open(im_path)
            h = im.size[1]
            w = im.size[0]
            xs = xys[:4]
            ys = xys[4:]

            xs_i = [int(float(i) * w) for i in xs]
            ys_i = [int(float(i) * h) for i in ys]

            # print(xs_i)
            # print(ys_i)

            imshow(im)
            plot([xs_i[0], xs_i[1], xs_i[2], xs_i[3], xs_i[0]], [ys_i[0], ys_i[1], ys_i[2], ys_i[3], ys_i[0]], 'r')
            if im_save:
                out_path = os.path.join(input_dir,"out/")
                if os.path.exists(out_path) is False:
                    os.makedirs(out_path)
                plt.savefig(
                    os.path.join(out_path, "{}-{}.jpg".format(os.path.splitext(os.path.basename(im.filename))[0]
                                                                  , time.time())))
            else:
                show()
            plt.cla()

if __name__ == '__main__':
    # visualise_dir('/home/leo/Downloads/datas/gen_wpod_det_trainset/detected/',im_save=True)
    visualise_dir('/home/leo/Downloads/datas/in5meter_plate/detected',im_save=True)
    # visualise_dir('./anno_eg',im_save=False)